<template>
  <div class="confirm">
    <!-- 顶部导航栏 -->
    <div class="header">
      <van-sticky>
        <van-nav-bar
          title="订单确认"
          left-text="返回"
          left-arrow
          @click-left="onClickLeft"
        />
      </van-sticky>
    </div>
    <div class="content">
      <div class="content_item" @click="showAddress">
        <div class="title">
          <van-icon name="location-o" />
          服务地址
          <br />
          <span>姓名：{{ name }} 电话：{{ tel }}</span>
          <br />
          <span>地址：{{ addr }}</span>
        </div>
        <div></div>
      </div>
      <div class="content_item">
        <van-icon name="orders-o" />
        订单详情
        <br />
        <ul v-for="info in orderline" :key="info.productId">
          <li v-if="info.name">
            {{ info.name }} ￥{{ info.pri }} x{{ info.num }}
          </li>
          <li v-else></li>
        </ul>
        <div style="margin-left: 60%">总计：￥{{ total }}</div>
      </div>
      <div class="content_item" @click="showTime">
        <van-icon name="clock-o" />
        服务时间
        <br />
        <div style="margin: 10px">
          {{ time | fmtDate }}
        </div>
      </div>
      <van-button
        round
        type="info"
        color="linear-gradient(to right, #8E54E9, #8E54E9)"
        style="top: 30px; margin-left: 25%; width: 200px"
        @click="Submit"
        >确认提交</van-button
      >
    </div>
    <van-action-sheet v-model="show" title="选择地址">
      <div class="content">
        <van-address-list
          v-model="aId"
          :list="addressList()"
          @select="Select"
          @add="onAdd"
          add-button-text="确的"
        />
      </div>
    </van-action-sheet>
    <van-action-sheet v-model="show1">
      <van-datetime-picker
        v-model="currentDate"
        type="datetime"
        :min-date="minDate"
        @cancel="cancel"
        @confirm="confirm"
      />
    </van-action-sheet>
  </div>
</template>

<script>
import { Dialog } from 'vant';
import { get, post,post_json } from "@/http/axios";
import moment from "moment";
// 引入vuex辅助函数
import { mapActions, mapGetters, mapMutations, mapState } from "vuex";
export default {
  // 局部注册
  filters: {
   
    fmtDate(date) {
      return moment(date).format("YYYY-MM-DD HH:mm:ss");
      // 或者return⾃⼰编写的时间处理函数
    },
  },
  data() {
    return {
      oId: "",
      aId: "",
      name: "",
      tel: "",
      addr: "",
      //地址中间量
      Aid: "",
      Name: "",
      Tel: "",
      Addr: "",
      show: false,
      show1: false,
      addressData: [],
      orderline: this.$route.query.addressList,

      total: this.$route.query.total,
      currentDate: new Date(),
      minDate: new Date(),
      time: "",
    };
  },
  computed: {
    ...mapState("user", ["userInfo"]),
    ...mapState("shopcart",["orderLines"])
  },
  methods: {
    ...mapActions("user", ["getUserInfo"]),
    ...mapMutations("shopcart",["clearShopcart"]),
    // 过滤number数量为0 的商品
    isNumber() {
      let userorderLines = [];
      for (let orderLine of this.orderLines.values()) {
        let data = { ...orderLine };
        console.log(data);
        if (data.number != 0) {
          userorderLines.push(data);
        }
      }
      return userorderLines;
    },
    //提交订单
    async Submit() {
      //console.log(this.address);
      let userorderLines = this.isNumber();
      let data = {
        addressId: this.oId,
        customerId: this.userInfo.id,
        orderLines: userorderLines,
        serviceTime: this.getTimestamp(this.currentDate),
      };
      if (this.total == 0) {
        Dialog({ message: '请选择服务' });
        return;
      }
      if (this.total > this.userInfo.balance) {
        Dialog.confirm({
          title: "余额不足",
          message: "是否充值",
        })
          .then(() => {
            this.$router.push({
              path: "/manager/mine",
            });
          })
          .catch(() => {});
      } else {
        // console.log(data);
        this.userInfo.balance -= this.total;
        //  修改钱包里面的钱
        this.updateInfo();
        // 将订单提交
        let res = await post_json("/order/submitOrder", data);
        // 清空购物车
        this.clearShopcart();
        this.$router.push({
          path: "/manager/order",
        });
      }
    },
    // 扣除钱包钱
    async updateInfo() {
      let res = await post("/baseUser/saveOrUpdate", this.userInfo);
    },
    //
    formatter(type, val) {
      if (type === "month") {
        return `${val}月`;
      } else if (type === "day") {
        return `${val}日`;
      } else if (type === "year") {
        return `${val}年`;
      } else if (type === "hour") {
        return `${val}点`;
      } else if (type === "minute") {
        return `${val}分`;
      }
      return val;
    },
    getTimestamp(time) {
      //把时间日期转成时间戳 方法
      return new Date(time).getTime();
    },
  //返回上一个页面
    onClickLeft() {
      this.$router.go(-1);
    },
    async getAddress() {
      let data = {
        page: 1,
        pageSize: 50,
      };
      let res = await get("/address/pageQuery", data);
      this.addressData = res.data.data;
      this.oId = res.data.data.list[0].id;
      this.name = res.data.data.list[0].username;
      this.tel = res.data.data.list[0].telephone;
      this.addr = res.data.data.list[0].address;
    },
    showAddress() {
      this.show = true;
      this.aId = this.oId;
    },
    showTime() {
      this.show1 = true;
    },
    addressList() {
      // 筛选地址数据 生成匹配组件的数据
      let addressArr = this.addressData.list;
      let addressList = [];
      if (!addressArr) {
        return;
      }
      addressArr.forEach((item, index) => {
        let addressObj = {};
        (addressObj.id = item.id),
          (addressObj.name = item.username),
          (addressObj.tel = item.telephone),
          (addressObj.address =
            item.province + item.city + item.area + item.address),
          (addressObj.isDefault = item.isDefault);
        addressList.push(addressObj);
      });
      return addressList;
    },
    Select(item, index) {
      this.Aid = item.id;
      this.Name = item.name;
      this.Tel = item.tel;
      this.Addr = item.address;
    },
    onAdd() {
      this.aId = this.Aid;
      this.name = this.Name;
      this.tel = this.Tel;
      this.addr = this.Addr;
      this.oId = this.aId;
      this.show = false;
    },
    cancel() {
      this.show1 = false;
    },
    confirm(value) {
      this.time = value;
      this.show1 = false;
    },
  },

  created() {
    this.getAddress();
    this.time = this.currentDate;
    this.getUserInfo();
  },
};
</script>

<style scoped>
.content_item {
  box-shadow: 0 2px 5px 0 rgba(189, 22, 255, 0.425);
  border-radius: 3px;
  margin: 10px;
  padding: 15px;
}
.van-icon-edit {
  display: none;
}
</style>